import React, { useEffect, useState } from "react";
import styles from "./index.module.scss";
import {
  Form,
  Input,
  Button,
  Dialog,
  Switch,
  Toast,
  Skeleton,
  Modal
} from "antd-mobile";
import dayjs from "dayjs";
import type { DatePickerRef } from "antd-mobile/es/components/date-picker";

// 路由
import { redirect, useNavigate } from "react-router-dom";

// 导入仓库
import {
  myUserToken, phoneOpenid,
} from "@/store/userSlice";

// 导入带有类型的属性，方法 1.
import { useAppDispatch, useAppSelector } from "../../hooks";

// 请求
import {
  ApiCheckLogin,
  ApiMemberCarAdd,
  ApiMemberCarList,
  ApiMemberCarUpdate,
  ApiMemberCarUpdateStatus,
  ApiMemberInfo,
  ApiMemberUpdate,
} from "@/utils/api";

import LicenseKeyboard from "./keyboard/index";
import "./keyboard/style.scss";


export default () => {
  // 表单更新
  const [form] = Form.useForm();
  // 导入仓库 2.使用属性
  const userToken = useAppSelector(myUserToken);
  // const user = useAppSelector(storeUser);
  const myOpenid = useAppSelector(phoneOpenid);


  // 导入仓库 2.使用方法
  // const dispatch = useAppDispatch();

  // 路由跳转
  const navigate = useNavigate();
  // 检查并登录的member_id
  const [member_id, setMember_id] = useState(-1);

  // 输入车牌号
  const [memberVal, setMemberVal] = useState("");
  // 会员车辆
  const [member, setMember] = useState<Datum>({});
  // 骨架屏
  const [loading, setLoading] = useState(true);

  // 请求登录状态
  // const checkLogin = async () => {
  //   console.log(userToken.openid, "openid");
  //   const res = await ApiCheckLogin(userToken.openid);
  //   if (res.code == 0) {
  //     // 当前页面使用
  //     setMember_id(res.data.member_id);
  //     return res.data.member_id;
  //   } else {
  //     console.log("未登录");
  //     navigate("/home");
  //     return;
  //   }
  // };
// const checkLogin = async () => {
//   if (!myOpenid) {
//     // 去到注册页
//     localStorage.removeItem("encryptedUserToken");
//     navigate("/register");
//     // console.error("/register");
//   }
//   console.log(myOpenid, "openid");
//   // console.log(formData, "formData");
//   // 暂时先用手机号+
//   const res = await ApiCheckLogin(myOpenid);
//   if (res.code == 0) {
//     //  存到仓库？
//     // console.log(res.data.member_id, "member_id");
//     // 当前页面使用
//     setMember_id(res.data.member_id);
//     // await getMemberInfo(res.data.member_id);
//     return res.data.member_id;
//   } else {
//     console.log("未登录");
//     return;
//   }
// };
 const checkLogin = async () => {
    if (!myOpenid) {
      // 去到注册页
      localStorage.removeItem("encryptedUserToken");
      navigate("/register");
      // console.error("/register");
    }
    console.log(myOpenid, "openid");
    // console.log(formData, "formData");
    // 暂时先用手机号+
    const res = await ApiCheckLogin(myOpenid);
    if (res.code == 0) {
      //  存到仓库？
      // console.log(res.data.member_id, "member_id");
      // 当前页面使用
      setMember_id(res.data.member_id);
      // await getMemberInfo(res.data.member_id);
      // 用于后续 获取会员详情信息
      console.log(res.data.member_id);
      // await getMemberInfo(res.data.member_id);
      return res.data.member_id;
    } else {
      console.log("未登录");
      return;
    }
  };
  // 输入车牌号 或修改车牌号
  const changeMember = async (val) => {
    // 创建新的 member ，更新 plate_number
    const newMember = { ...member, plate_number: val };
    // 更新 member 状态
    setMember(newMember);
    // console.log(item.plate_number);
  };

  // 跳转主页
  const determine = async () => {
    if (member.plate_number == memberVal) {
      // navigate("/home");
      navigate("/home", { replace: true });
      return;
    }
    // 是否保存？
    const result = await Modal.confirm({
      content: "是否保存车牌号" + member.plate_number,
    });
    // 确认修改
    if (result) {
      await ApiMemberCarUpdate({
        member_car_id: member.id!,
        plate_number: member.plate_number!,
      });
      // 提示
      Toast.show({
        content: "更新" + member.plate_number + "成功",
        icon: "success",
      });
      // await mapMemberCarList();
      // navigate("/home");
      navigate("/home", { replace: true });
    } else {
      Toast.show({ content: "已取消更新", icon: "success" });
    }
    // 返回主页
  };

  // 车辆详情 二次处理数据
  const mapMemberCarList = async () => {
    const res = await ApiMemberCarList();
    const data = res.data.filter((item) => item.status == 1)[0];
    console.log(data);
    setMember({ ...data, plate_number:''});
    setMemberVal(data.plate_number);
  };

  // 车辆详情
  const getMemberCarList = async () => {
    // 请求车辆列表
    try {
      // 二次处理
      await mapMemberCarList();
    } finally {
      // 无论请求成功或失败，都设置 loading 为 false
      // 使用骨架屏
      setLoading(false);
    }
  };

  // 检查登录 获取member_id
  const initData = async () => {
    // 请求用户信息
    // getAccessToken();
    const member_id = await checkLogin();
    if (!member_id) return;
    // 用于后续 获取会员详情信息
    // await getMemberInfo(member_id);
    // 请求车辆列表
    getMemberCarList();
  };

  // 挂载页面
  useEffect(() => {
    // 检查登录 获取member_id
    initData();
  }, []);

  // 设置默认值+监听
  useEffect(() => {
    // 更新表单
    form.setFieldsValue(member);
  }, [member]);

  return (
    <div className={styles.form}>
      {/* <Skeleton.Title animated /> */}
      <Skeleton.Paragraph
        animated
        lineCount={15}
        style={{ display: loading ? "block" : "none" }}
      />
      {/* <h4 style={{ display: loading ? "none" : "block", marginLeft: "5px" }}>
        车牌号管理
      </h4> */}
      <Form
        style={{ display: loading ? "none" : "block" }}
        initialValues={{ ...member, memberVal }}
        layout="horizontal"
        form={form}
      >
        <Form.Header>当前车牌号</Form.Header>
        <Form.Item
          label="当前车牌号"
          style={{ display: memberVal ? "block" : "none" }}
        >
          <Input
            value={memberVal}
            placeholder="请输入新车牌"
            // onChange={(val) => changeMember(val)}
            disabled
          ></Input>
        </Form.Item>
        <Form.Item
          name="created_at"
          label="创建时间"
          style={{
            display: member?.id ? "inline-block" : "none",
          }}
        >
          <Input
            placeholder={dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss")}
            disabled
          />
        </Form.Item>
        <Form.Item
          name="updated_at"
          label="更新时间"
          style={{
            display: member?.id ? "inline-block" : "none",
          }}
        >
          <Input
            placeholder={dayjs(Date.now()).format("YYYY-MM-DD HH:mm:ss")}
            disabled
          />
        </Form.Item>
      </Form>
      <Form
        style={{
          display: loading ? "none" : "block",
          marginTop: "20px",
          position: "relative",
        }}
        initialValues={{ ...member, memberVal }}
        layout="horizontal"
        form={form}
        footer={
          <Button
            block
            type="submit"
            color="primary"
            size="large"
            shape="rounded"
            onClick={determine}
            // style={{ position: "relative", top: "160px" }}
          >
            保存
          </Button>
        }
      >
        <Form.Header>车牌号修改</Form.Header>
        <Form.Item name="plate_number" label="使用新车牌">
          <Input
            placeholder="输入新车牌号"
            onChange={(val) => changeMember(val)}
            // disabled={member[index]?.isEdit}
          ></Input>
        </Form.Item>
      </Form>
    </div>
  );
};